package com.beep.erp;

import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v4.app.Fragment;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TabHost;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.beep.erp.common.base.BaseActivity;
import com.beep.erp.common.base.ToolbarActivity;
import com.beep.erp.common.base.simpleactivity.SimpleBackActivity;
import com.beep.erp.common.base.simpleactivity.SimpleBackPage;
import com.beep.erp.common.bean.UpdateBean;
import com.beep.erp.common.rx.permission.RxPermissions;
import com.beep.erp.common.utils.AppManager;
import com.beep.erp.common.utils.ToastUtils;
import com.beep.erp.common.utils.ToolsUtils;
import com.beep.erp.common.widget.BottomNavigationBar;
import com.beep.erp.model.home.HomeFragment;
import com.beep.erp.model.mine.MineFragment;
import com.beep.erp.model.purchase.BlankFragment;
import com.beep.erp.model.stock.StockFragment;
import com.beep.erp.model.update.service.DownLoadService;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import rx.Observable;

public class MainActivity extends BaseActivity<MainPresenter, MainModel> implements MainContract.View, TabHost.OnTabChangeListener, View.OnTouchListener {

    @BindView(R.id.realtabcontent)
    FrameLayout realtabcontent;
    @BindView(R.id.tabhost)
    BottomNavigationBar tabhost;

    private ArrayList<MainModel.MainBean> t = new ArrayList<>();
    private long mBackPressedTime;

    public static void start(Context context) {
        Intent intent = new Intent(context, MainActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_main;
    }

    @Override
    protected void initView() {
        tabhost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);
        if (Build.VERSION.SDK_INT > 10) {
            tabhost.getTabWidget().setShowDividers(0);
        }
        tabhost.setCurrentTab(0);
        tabhost.setOnTabChangedListener(this);
    }

    @Override
    public void onBackPressed() {
        long curTime = SystemClock.uptimeMillis();
        if ((curTime - mBackPressedTime) < (3 * 1000)) {
            appExit();
        } else {
            mBackPressedTime = curTime;
            ToastUtils.show(R.string.tip_double_click_exit, 3000);
        }
    }

    private void appExit() {
        stopService(new Intent(AppContext.context(), DownLoadService.class));
        AppManager.getAppManager().AppExit(this);
        ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
        am.killBackgroundProcesses("com.beep.erp");
    }

    @Override
    public void getDate() {
        showShare();
    }

    @Override
    public void getTabs() {
        setTab();
    }

    /**
     * 版本更新
     */
    private void showShare() {
        RxPermissions.getInstance(this)
                .request(Constants.SHARE_PERMISSION_LIST)
                .subscribe(granted -> {
                    if (granted) {
                        mPresenter.updateVison();
                    } else {
                        new MaterialDialog.Builder(this)
                                .title(R.string.help)
                                .content(R.string.string_help_text)
                                .positiveText(R.string.quit)
                                .onPositive((dialog, which) -> appExit())
                                .show();
                    }
                });
    }

    @Override
    public void updateVision(UpdateBean updateBean) {

        if (BuildConfig.VERSION_CODE < updateBean.getVersion() & updateBean.getIsUpdate() == 2) {
            showPopup(updateBean, "退出");
            return;
        }
        /*if (BuildConfig.VERSION_CODE < updateBean.getVersion() & NetUtils.isWifiConnected(this) & updateBean.getIsUpdate() == 1) {
            Intent intent = new Intent(MainActivity.this, DownLoadService.class);
            intent.putExtra(Constants.BUNDLE_KEY_TITLE, updateBean.getApkUrll());
            startService(intent);
            return;
        }*/
        if (BuildConfig.VERSION_CODE < updateBean.getVersion()) {
            showPopup(updateBean, "稍后再说");
        }
    }

    private void showPopup(UpdateBean updateBean, String clear) {
        View contentView = LayoutInflater.from(this).inflate(R.layout.update_dialog, null);
        final PopupWindow update = new PopupWindow(contentView,
                LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT,
                true);
        update.setContentView(contentView);
        update.setBackgroundDrawable(new BitmapDrawable());
        update.showAtLocation(contentView, Gravity.CENTER, 0, 0);
        backgroundAlpha(0.3f);

        TextView textViewVersion = (TextView) update.getContentView().findViewById(R.id.tv_version);
        TextView textViewUpdate = (TextView) update.getContentView().findViewById(R.id.tv_update);
        TextView textViewClear = (TextView) update.getContentView().findViewById(R.id.tv_clear);
        textViewClear.setText(clear);
        TextView textViewUpdate2 = (TextView) update.getContentView().findViewById(R.id.tv_update_info2);
        textViewUpdate2.setText(updateBean.getUpgradePoint());
        textViewVersion.setText("版本更新：" + updateBean.getVersionCode());
        update.setAnimationStyle(R.style.take_photo_anim);
        update.setOnDismissListener(() -> backgroundAlpha(1f));
        textViewUpdate.setOnClickListener(v1 -> {
            Intent intent = new Intent(MainActivity.this, DownLoadService.class);
            intent.putExtra(Constants.BUNDLE_KEY_TITLE, updateBean.getApkUrll());
            startService(intent);
            update.dismiss();
        });
        textViewClear.setOnClickListener(v12 -> {
            if (updateBean.getIsUpdate() == 2) {
                AppManager.getAppManager().AppExit(this);
            } else {
                update.dismiss();
            }
        });
    }

    public void backgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = bgAlpha; //0.0-1.0
        getWindow().setAttributes(lp);
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void showMessage(String message) {

    }

    public void setTabSelection(int index) {
        tabhost.setCurrentTab(index);
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        super.onTouchEvent(event);
        boolean consumed = false;
        if (event.getAction() == MotionEvent.ACTION_DOWN
                && v.equals(tabhost.getCurrentTabView())) {
            Fragment currentFragment = getCurrentFragment();
            if (currentFragment != null
                    && currentFragment instanceof BottomNavigationBar.OnTabReselectListener) {
                BottomNavigationBar.OnTabReselectListener listener = (BottomNavigationBar.OnTabReselectListener) currentFragment;
                listener.onTabReselect();
                consumed = true;
            }
        }
        return consumed;
    }

    private Fragment getCurrentFragment() {
        return getSupportFragmentManager().findFragmentByTag(
                tabhost.getCurrentTabTag());
    }

    @Override
    public void onTabChanged(String s) {
        final int size = tabhost.getTabWidget().getTabCount();
        for (int i = 0; i < size; i++) {
            View v = tabhost.getTabWidget().getChildAt(i);
            if (i == tabhost.getCurrentTab()) {
                //   getTvTitle().setText(tabId);
                v.setSelected(true);
            } else {
                v.setSelected(false);
            }
        }
    }

    private void setTab() {
        if (tabhost == null || tabhost.getTabWidget() == null) return;
        t.clear();
        tabhost.clearAllTabs();
        t.add(new MainModel.MainBean(0, R.string.main_tab_name_home, R.drawable.bottom_bar_main_home, HomeFragment.class));
        t.add(new MainModel.MainBean(1, R.string.main_tab_name_order, R.drawable.bottom_bar_main_rank, StockFragment.class));
        t.add(new MainModel.MainBean(2, R.string.main_tab_name_person, R.drawable.bottom_bar_main_my, MineFragment.class));
        setBottomTab();
    }

    private void setBottomTab() {
        tabhost.clearAllTabs();
        for (MainModel.MainBean mainBean : t) {
            TabHost.TabSpec tab = tabhost.newTabSpec(getString(mainBean.getResName()));
            View indicator = View.inflate(this, R.layout.tab_indicator, null);
            TextView title = (TextView) indicator.findViewById(R.id.tab_title);
            ImageView icon = (ImageView) indicator.findViewById(R.id.iv_icon);
            icon.setImageResource(mainBean.getResIcon());
            if (ToolsUtils.isEmpty(getString(mainBean.getResName()))) {
                title.setVisibility(View.GONE);
            } else {
                title.setVisibility(View.VISIBLE);
            }
            title.setText(getString(mainBean.getResName()));
            tab.setIndicator(indicator);
            tabhost.addTab(tab, mainBean.getClz(), null);
            tabhost.getTabWidget().getChildAt(mainBean.getIdx()).setOnTouchListener(this);
        }
    }
}
